package org.wpahs.ahn.rssfeed;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import org.wpahs.ahn.rssfeed.DB.DBMyFeed;

import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;


public class CurrentFeedsFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    TextView mEditName=null;
    TextView mEditUrl=null;
    TextView mEditLastUpdated = null;
    TextView mEditDescription = null;
    ImageView mEditImage = null;
    private Button mBtnRemove=null;

    SimpleDateFormat s = new SimpleDateFormat("MM.dd.yyyy hh:mm", Locale.getDefault());

    FeedAdapter mAdapter = null;
    private ListView mEditListView = null;
    List<MyFeed> mFeeds = null;

    private OnFragmentInteractionListener mListener;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *

     * @return A new instance of fragment FindFeedFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static CurrentFeedsFragment newInstance() {
        CurrentFeedsFragment fragment = new CurrentFeedsFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    public CurrentFeedsFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_currentfeeds, container, false);
        mEditListView = (ListView)v.findViewById(R.id.EditFeedList);
        setupUI(v);
        return v;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    private void LoadFeeds(){
        DBMyFeed db= new DBMyFeed(getActivity());
        mFeeds = db.GetFeeds(false);
        db.close();
        mAdapter = new FeedAdapter(getActivity(),R.layout.editfeed_layout,mFeeds);
        mEditListView.setAdapter(mAdapter);

        mAdapter.notifyDataSetInvalidated();
    }

    private void setupUI(View v){
        mEditListView=(ListView)v.findViewById(R.id.EditFeedList);
        LoadFeeds();
    }

    public class FeedAdapter extends ArrayAdapter<MyFeed> {
        Context mContext;

        public FeedAdapter(Context context, int resource, List<MyFeed> objects) {
            super(context, resource, objects);
            mContext = context;

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final View feedView = inflater.inflate(R.layout.editfeed_layout, parent, false);
            org.wpahs.ahn.rssfeed.MyFeed feed = this.getItem(position);

            mEditName = (TextView)feedView.findViewById(R.id.EditTitle);
            mEditUrl = (TextView)feedView.findViewById(R.id.EditUrl);
            mEditLastUpdated=(TextView)feedView.findViewById(R.id.EditLastUpdated);
            mEditDescription=(TextView)feedView.findViewById(R.id.EditDescription);
            mBtnRemove=(Button)feedView.findViewById(R.id.EditRemove);
            mEditImage = (ImageView)feedView.findViewById(R.id.EditImage);

            mEditName.setText(feed.getTitle());
            mEditUrl.setText(feed.getUrl());
            mEditDescription.setText(feed.getSubtitle());
            mBtnRemove.setHint(feed.getUrl());

            if(feed.getLastUpdated() != null){
                mEditLastUpdated.setText(s.format(feed.getLastUpdated()));
            }else{
                mEditLastUpdated.setText("Never Updated");
            }

            mEditImage.setImageBitmap(decodeBase64(feed.getImage()));

            mBtnRemove.setId(feed.getId());
            mBtnRemove.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        DBMyFeed db = new DBMyFeed(v.getContext());
                        db.deleteFeed( v.getId());
                        db.close();
                        LoadFeeds();
                        //getActivity().feedRemoved(mBtnRemove.getId());
                    }catch (Exception ex){
                        Log.e("On Delete Feed", ex.getMessage());
                        ((Button) v).setError(ex.getMessage());
                    }
                }
            });
            feedView.setTag(feed.getUrl());
            // do UI
            feedView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    android.content.ClipboardManager clipboard =
                            (android.content.ClipboardManager)getActivity().getSystemService(
                                    Context.CLIPBOARD_SERVICE
                            );
                    android.content.ClipData clip =
                            android.content.ClipData.newPlainText("grurl",(String)v.getTag());
                    clipboard.setPrimaryClip(clip);

                    Toast.makeText(v.getContext(), v.getTag() + " has been copied to your clipboard.", Toast.LENGTH_SHORT).show();
                    return true;
                }
            });

            return feedView;
        }
        private Bitmap decodeBase64(String input) {
            Bitmap retval = null;
            try {
                if (input != null) {
                    byte[] decodedByte = Base64.decode(input, 0);
                    retval = BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
                }

            }catch(OutOfMemoryError oomex){
                oomex.printStackTrace();

            }catch (Exception ex) {
                ex.printStackTrace();
            }
            return retval;
        }
    }

    public void tellFeedDone(int feedId){
        int position = -1;
        for(int x = 0; x<mFeeds.size(); x++){
            if(mFeeds.get(x).getId() == feedId){
                position = x;
                break;
            }
        }
        if(position >=0) {
            View v = mAdapter.getView(position,null,mEditListView);
        }
    }



}
